package jsu.lipengcheng.trafficnet.Util;

import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

public class RideslockUtil implements rideslock{
    private String name;

    private RedisTemplate redisTemplate;

    public RideslockUtil(String name, RedisTemplate redisTemplate) {
        this.name = name;
        this.redisTemplate = redisTemplate;
    }

    private static final String KEY_PREFIX="lock:";
    private static final String ID_PREFIX= UUID.randomUUID().toString()+"-";
    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;
    static {
        UNLOCK_SCRIPT=new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
        UNLOCK_SCRIPT.setResultType(Long.class);
    }

    @Override
    public void unlock() {
        //获取线程表示
//        String threadname=ID_PREFIX + Thread.currentThread().getName();
//       String id =(String) redisTemplate.opsForValue().get(KEY_PREFIX + name);
//       if (threadname.equals(id)){
//           redisTemplate.delete(KEY_PREFIX + name);
//       }
        redisTemplate.execute(
                UNLOCK_SCRIPT,
                Collections.singletonList(KEY_PREFIX + name),
                ID_PREFIX + Thread.currentThread().getName()
                );
    }

    @Override
    public boolean trylock(long time) {
        //获取线程标识
        String threadname =ID_PREFIX + Thread.currentThread().getName();
        Boolean success= redisTemplate.opsForValue().setIfAbsent(KEY_PREFIX + name,threadname,time, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(success);
    }
}
